﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Text.RegularExpressions;
using YXShop.TemplateAction;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace YXShop.Web.admin.templates
{
    public partial class template : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            YXShop.Common.PromptInfo.Popedom("011001001");
            if (ChangeHope.WebPage.PageRequest.GetFormString("Option") != string.Empty)
            {
                string types = Request.Form["Option"].Trim();
                int id = ChangeHope.WebPage.PageRequest.GetFormInt("id");
                string templatepath = ChangeHope.WebPage.PageRequest.GetFormString("TemPath");
                if (types == "template"&&id>0)
                {
                    SetTemplate(templatepath,id);
                }
                else if (types == "PutoutFemplate")
                {
                    ReadTemptale(templatepath);
                }
                Response.End();
                return;
            }
            if (!IsPostBack)
            {
                if (ChangeHope.WebPage.PageRequest.GetQueryString("type") == "downloadTemplate")
                {
                    string templatepath = ChangeHope.WebPage.PageRequest.GetQueryString("templatePath");
                    DownloadTemplate(templatepath);
                }
                this.Literal2.Text = DefaultGetList();
                this.Literal1.Text = GetList();
            }
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        protected string GetList()
        {
            YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
            ChangeHope.WebPage.Table table = new ChangeHope.WebPage.Table();
            YXShop.BLL.SystemInfo.ShopStyle data = new YXShop.BLL.SystemInfo.ShopStyle();
            ChangeHope.DataBase.DataByPage dataPage = data.GetList();
            StringBuilder shtml = new StringBuilder();
            //添加表的内容
            if (dataPage.DataReader != null)
            {
                shtml.Append("<table width='100%'  bgcolor=\"#F5F5F5\">");
                shtml.Append("<tr>");
                int count = 0;
                while (dataPage.DataReader.Read())
                {
                    count++;
                    shtml.Append("<td width=\"170px\">");
                    shtml.Append("<table width=\"100%\" border=\"0\" cellspacing=\"3\" cellpadding=\"3\" width='170px'>");
                    shtml.Append("<tr>");
                    shtml.Append("<td style='border: 1px solid #999999;' align='Center'>" + string.Format("<a href='stencil_list.aspx?templateId={2}&name={1}'><img src='{0}' border='0' title='点击编辑此模板'/></a>", sp.DummyPaht+dataPage.DataReader["SampleMapPath"].ToString(), dataPage.DataReader["TemplatePath"].ToString(), dataPage.DataReader["id"].ToString()) + "</td>");
                    shtml.Append("</tr>");
                    shtml.Append("<tr>");
                    shtml.Append("<td align='Center'>" + string.Format("<strong>{0}({1})</strong>", dataPage.DataReader["Name"].ToString(), dataPage.DataReader["Version"].ToString()) + "</td>");
                    shtml.Append("</tr>");
                    shtml.Append("<tr>");
                    shtml.Append("<td align='Center'>" + string.Format("<a href='http://www.yx-shop.cn' target='_blank'>YxShop</a>|<span style='color:#666'>{0}</span>", dataPage.DataReader["CrateTime"].ToString()) + "</td>");
                    shtml.Append("</tr>");
                    shtml.Append("<tr>");
                    shtml.Append("<td align='Center'>" + string.Format("<a href='label/labelclass_list.aspx?w_d_isstorelabel=0&w_d_styleid={1}&q_templatepath={0}'>标签</a>&nbsp;|&nbsp;<a href='stencil_list.aspx?templateId={1}&name={0}' title='编辑模板'>编辑</a>&nbsp;|&nbsp;<a href=\"javascript:DefaultTemplate({1},'{0}')\"' title='启用此模板'>启用</a>&nbsp;|&nbsp;<a href=\"?type=downloadTemplate&templatePath={0}\" title='下载此模板'>下载</a>", dataPage.DataReader["TemplatePath"].ToString(), dataPage.DataReader["id"].ToString()) + "</td>");
                    shtml.Append("</tr>");
                    shtml.Append("</table>");
                    shtml.Append("</td>");
                    if (count % 4 == 0)
                    {
                        shtml.Append("</tr><tr>");
                    }
                }
                shtml.Append("</tr>");
                shtml.Append("</table>");
            }
            dataPage.Dispose();
            dataPage = null;
            return shtml.ToString();
        }

        /// <summary>
        /// 默认模板
        /// </summary>
        /// <returns></returns>
        protected string DefaultGetList()
        {
            YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
            ChangeHope.WebPage.Table table = new ChangeHope.WebPage.Table();
            YXShop.BLL.SystemInfo.ShopStyle data = new YXShop.BLL.SystemInfo.ShopStyle();
            ChangeHope.DataBase.DataByPage dataPage = data.GetList();
            StringBuilder shtml = new StringBuilder();
            //添加表的内容
            if (dataPage.DataReader != null)
            {
                shtml.Append("<table width='100%'  bgcolor=\"#F5F5F5\">");
                shtml.Append("<tr>");
                while (dataPage.DataReader.Read())
                {
                    if (dataPage.DataReader["IsDefault"].ToString() == "1")
                    {
                        shtml.Append("<td style='border: 1px solid #999999;' align='Center'>" + string.Format("<a href='stencil_list.aspx?templateId={2}&name={1}'><img src='{0}' border='0' title='点击编辑此模板'/></a>", sp.DummyPaht+dataPage.DataReader["SampleMapPath"].ToString(), dataPage.DataReader["TemplatePath"].ToString(), dataPage.DataReader["id"].ToString()) + "</td>");
                        shtml.Append("<td valign=\"top\"  width='170px'>");

                        shtml.Append("<table width=\"100%\" border=\"0\" cellspacing=\"3\" cellpadding=\"3\">");
                        shtml.Append("<tr>");
                        shtml.Append("<td>" + string.Format("<strong>{0}({1})</strong>", dataPage.DataReader["Name"].ToString(), dataPage.DataReader["Version"].ToString()) + "</td>");
                        shtml.Append("</tr>");
                        shtml.Append("<tr>");
                        shtml.Append("<td>提供者：<a href='http://www.yx-shop.cn' target='_blank'>YxShop</a></td>");
                        shtml.Append("</tr>");
                        shtml.Append("<tr>");
                        shtml.Append("<td>" + string.Format("<a href='stencil_list.aspx?templateId={1}&name={0}'>编辑模板</a>&nbsp;&nbsp;<a href=\"javascript:PutOutTemplate('{0}')\">发布模板</a>", dataPage.DataReader["TemplatePath"].ToString(), dataPage.DataReader["id"].ToString()) + "</td>");
                        shtml.Append("</tr>");
                        shtml.Append("</table>");

                        shtml.Append("</td>");
                        
                        shtml.Append("<td style=\"background-color:#EBEEE7; border:solid #BCC7C3 1px\">");
                        shtml.Append("<div>");
                        shtml.Append("<h5>模板使用说明：</h5>");
                        shtml.Append("<ul>");
                        shtml.Append("<li>一个商城，仅能同时使用一套模板；</li>");
                        shtml.Append("<li>在页面下方有多个模板可供使用，可以点击启用，即该模板就设为默认模板；</li>");
                        shtml.Append("<li>点击页面上方的“浏览网站”按钮，即可看到此模板在前台的显示效果。</li>");
                        shtml.Append("</ul>");
                        shtml.Append("</div>");
                        shtml.Append("</td>");
                    }

                }
                shtml.Append("</tr>");
                shtml.Append("</table>");
            }
            dataPage.Dispose();
            dataPage = null;
            return shtml.ToString();
        }

        private void SetTemplate(string Template, int id)
        {
            YXShop.BLL.SystemInfo.ShopStyle data = new YXShop.BLL.SystemInfo.ShopStyle();
            YXShop.BLL.SystemInfo.WebSetting dataws = new YXShop.BLL.SystemInfo.WebSetting();
            ChangeHope.DataBase.DataByPage dataPage = data.GetList();
            if (dataPage.DataReader != null)
            {
                while (dataPage.DataReader.Read())
                {
                    if (dataPage.DataReader["id"].ToString() == id.ToString())
                    {
                        if (data.Amend(id, "IsDefault", 1) != 0)
                        {
                            if (Template.Substring(0, Template.IndexOf("/")) == "templates")
                            {
                                Template = "template" + Template.Substring(Template.IndexOf("/"), Template.Length - Template.IndexOf("/"));
                            }
                            if (dataws.Amend(1, "tmplatepath", Template) != 0)
                            {
                                ChangeHope.Common.CacheClass.RemoveOneCache("WebSetting");//清除缓存
                                Response.Write("Ok");
                            }
                        }
                    }
                    else
                    {
                        data.Amend(Convert.ToInt32(dataPage.DataReader["id"].ToString()), "IsDefault", 0);
                    }
                }
            }
        }

        #region 发布模板
        private void PutoutTemplate(string Path)
        {
            DirectoryInfo FatherDirectory = new DirectoryInfo(Server.MapPath("~/" + Path)); //当前目录
            DirectoryInfo[] ChildDirectory = FatherDirectory.GetDirectories("*.*"); //得到子目录集
            FileInfo[] NewFileInfo = FatherDirectory.GetFiles();
            ChangeHope.Common.FileHelper hf = new ChangeHope.Common.FileHelper();
            foreach (FileInfo fi in NewFileInfo)//显示文件
            {
                string filename = fi.Name;
                //原来文件路径加文件名
                string oldFilePath = Server.MapPath("~/" + Path) + "\\" + filename;
                //新文件路径加文件名
                string newsPath = Path;
                if (newsPath.Contains("templates/"))
                {
                    newsPath = newsPath.Replace("templates/", "");
                }
                string newsFilePath = Server.MapPath("~/template\\" + newsPath + "\\" + filename);
                
                if (filename.Contains(".htm") || filename.Contains(".html") || filename.Contains(".Shtml"))
                {
                    YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
                    string str_FilePath = ChangeHope.Common.ServerInfo.GetRootPath().Trim('\\');
                    YXShop.TemplateAction.Template indexTemp = new YXShop.TemplateAction.Template(oldFilePath);
                    indexTemp.GetHTML();
                    indexTemp.GetEidtLable(false);
                    indexTemp.BackPath("",Path);
                    string getContent = this.TemptaleContent(indexTemp.OriginalContent);
                    getContent = this.TemptaleContent(getContent);

                    if (Regex.Match(getContent, @"\</head\>[\s\S]*\<body", RegexOptions.IgnoreCase | RegexOptions.Compiled).Success)
                    {
                        getContent = Regex.Replace(getContent, "<body", "<body", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    }
                    //创建文件
                    if(hf.WriteFileContent(newsFilePath, getContent, true))
                    {

                    }
                }
                else
                {
                    if (!filename.Contains(".exe") || !filename.Contains(".scc"))
                    {
                        string fileOldPath = oldFilePath;
                        string fileNewPath = newsFilePath;
                        hf.CopyFile(fileOldPath, fileNewPath, true);
                    }
                }
            }
        }
        private void ReadTemptale(string path)
        {
            DirectoryInfo FatherDirectory = new DirectoryInfo(Server.MapPath("~/" + path)); //当前目录
            DirectoryInfo[] ChildDirectory = FatherDirectory.GetDirectories("*.*"); //得到子目录集
           this.PutoutTemplate(path);
            foreach (DirectoryInfo di in ChildDirectory)
            {
                ReadTemptale(path + "/" + di.Name);
            }
            
        }

        #region 解晰标签内容
        /// <summary>
        /// 解晰标签内容
        /// </summary>
        /// <param name="Content">模板内容</param>
        /// <returns></returns>
        private string TemptaleContent(string Content)
        {
            string pattern = @"\{\#[\s\S]*?\#\}";
            string _tempfinallyconent = Content;
            StringBuilder GetTemp = new StringBuilder();
            MatchCollection macths = Regex.Matches(_tempfinallyconent, pattern);
            foreach (Match macth in macths)
            {
                string temptag = "";
                temptag = macth.ToString();
                int templength = temptag.ToString().IndexOf("{#") + 2;
                int templength2 = temptag.ToString().IndexOf("#}");
                if (temptag.ToString().Substring(templength, templength2 - templength).ToString() != null && temptag.IndexOf("*") > -1)
                {
                    string Str_Tag = temptag.ToString().Substring(templength, templength2 - templength);//找到标签
                    string[] tempString = Str_Tag.Split('*');
                    string Tag_Name = tempString[0].ToString();//获得标签名称,在之后做调用前的比较。
                    string Tag_ID = tempString[1].ToString();//获取标签的参数
                    string[] tempid = YXShop.TemplateAction.Template.GetTagID(Tag_ID);//获取标签的参数列表并进行拆分
                    Template theLabel = null;
                    string labelContent = string.Empty;
                    switch (Tag_Name)
                    {
                        case "YXShopDefinTag":
                            theLabel = Template.GetLabel(Convert.ToString(tempid[0]), Tag_Name);
                            labelContent = theLabel.GetLabelContent();
                            _tempfinallyconent = _tempfinallyconent.Replace(temptag.Trim(), labelContent);
                            break;
                        case "YXShopRivetTag":
                            theLabel = Template.GetLabel(Convert.ToString(tempid[0]), Tag_Name);
                            labelContent = theLabel.GetLabelContent();
                            _tempfinallyconent = _tempfinallyconent.Replace(temptag.Trim(), labelContent);
                            break;
                        case "YXShopFreeTag":
                            theLabel = Template.GetLabel(Convert.ToString(tempid[0]), Tag_Name);
                            labelContent = theLabel.GetLabelContent();
                            _tempfinallyconent = _tempfinallyconent.Replace(temptag.Trim(), labelContent);
                            break;
                        default:
                            break;
                    }
                }
            }
            return _tempfinallyconent;
        }
        #endregion

        #endregion

        #region 下载模板
        ZipOutputStream zos = null;
        String strBaseDir = "";
        private void DownloadTemplate(string path)
        {
            string strFileName = path.Substring(path.LastIndexOf("/")+1,path.Length-path.LastIndexOf('/')-1);
            string strPath =Server.MapPath("~\\"+ path);
            
            MemoryStream ms = null;
            Response.ContentType = "application/octet-stream";
            strFileName = HttpUtility.UrlEncode(strFileName).Replace('+', ' ');
            Response.AddHeader("Content-Disposition", "attachment;   filename=" + strFileName + ".zip");
            ms = new MemoryStream();
            zos = new ZipOutputStream(ms);
            strBaseDir = strPath + "\\";
            addZipEntry(strBaseDir);
            zos.Finish();
            zos.Close();
            Response.Clear();
            Response.BinaryWrite(ms.ToArray());
            //Response.End();   
        }

        private void addZipEntry(string PathStr)
        {
            DirectoryInfo di = new DirectoryInfo(PathStr);
            foreach (DirectoryInfo item in di.GetDirectories())
            {
                addZipEntry(item.FullName);
            }
            foreach (FileInfo item in di.GetFiles())
            {
                FileStream fs = File.OpenRead(item.FullName);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                string strEntryName = item.FullName.Replace(strBaseDir, "");
                ZipEntry entry = new ZipEntry(strEntryName);
                zos.PutNextEntry(entry);
                zos.Write(buffer, 0, buffer.Length);
                fs.Close();
            }
        }  
        #endregion
    }
}
